
/*
 * Hlpay-Plus aggregate payment system. Copyright
 * (c) 2022-2023 Hlpay Team Copyright has the right of final interpretation.
 */

package com.hlkj.pay.controller.admin;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.LocalContext;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.pay.app.adminuser.IRoleAppService;
import com.hlkj.pay.app.transfer.RoleDoToResp;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.dto.LocalAdminUserRequest;
import com.hlkj.pay.dto.admin.RoleQueryDto;
import com.hlkj.pay.dto.common.DataFilterConfig;
import com.hlkj.pay.infrastructure.model.admin.AdminUserRoleMappingDO;
import com.hlkj.pay.infrastructure.model.admin.RoleDO;
import com.hlkj.pay.service.admin.IAdminUserService;
import com.hlkj.pay.service.admin.IRoleService;
import com.hlkj.pay.service.common.IPlatFormConfigService;
import com.hlkj.pay.vo.admin.req.role.RoleAddReq;
import com.hlkj.pay.vo.admin.req.role.RolePermissionReq;
import com.hlkj.pay.vo.admin.req.role.RoleQueryReq;
import com.hlkj.pay.vo.admin.req.role.RoleUpdateReq;
import com.hlkj.pay.vo.admin.resp.role.RoleDetailResp;
import com.hlkj.pay.vo.admin.resp.role.RoleResp;
import com.hlkj.pay.vo.common.req.DeleteCodeReq;

import cn.hutool.core.collection.CollUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2024/09/10 14:50
 */
@Tag(name = "角色配置")
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/v1/adminuser/role")
public class AdminRoleController extends BaseController {

    private final IAdminUserService userService;

    private final IRoleService roleService;

    private final IRoleAppService roleAppService;

    private final IPlatFormConfigService platFormConfigService;

    @Operation(summary = "角色分页列表")
    @GetMapping("/page")
    public CommonResult<PageResult<RoleResp>> queryRolePage(RoleQueryReq roleQueryReq) {
        RoleQueryDto roleQueryDto = new RoleQueryDto();
        roleQueryDto.setLikeName(roleQueryReq.getName());
        roleQueryDto.setCode(roleQueryReq.getCode());
        roleQueryDto.setPageNo(roleQueryReq.getPageNo());
        roleQueryDto.setPageSize(roleQueryReq.getPageSize());
        roleQueryDto.setSysType(roleQueryReq.getSysType());
        roleQueryDto.setSn(roleQueryReq.getSn());
        LocalAdminUserRequest localAdminUserRequest = (LocalAdminUserRequest) LocalContext.get();
        DataFilterConfig dataFilterConfig = platFormConfigService.getDataFilterConfig();
        List<DataFilterConfig.RoleFilter> roleFilters = dataFilterConfig.getRoleFilters();
        Map<Integer, List<DataFilterConfig.RoleFilter>> collect = roleFilters.stream().collect(Collectors.groupingBy(DataFilterConfig.RoleFilter::getSysType));
        List<DataFilterConfig.RoleFilter> roleFilterList = collect.get(localAdminUserRequest.getSysType());

        // 数据进行过滤
        if (!CollectionUtils.isEmpty(roleFilterList)) {
            DataFilterConfig.RoleFilter filter = roleFilterList.get(0);
            roleQueryDto.setFilterCodeList(filter.getRoleCodes());
        }

        boolean isAdmin = false;
        List<AdminUserRoleMappingDO> roleMappingDOList = userService.queryUserRoles(localAdminUserRequest.getUserId());
        if(CollUtil.isNotEmpty(roleMappingDOList)){
            List<String> roles = roleMappingDOList.stream().map(AdminUserRoleMappingDO::getRoleCode).collect(Collectors.toList());
            if(CollUtil.isNotEmpty(roles)){
                // 判断是否含有管理员权限
                isAdmin = roleAppService.isAdmin(roles,roleQueryReq.getSysType());
                if(!isAdmin){
                    roleQueryDto.setCodeList(roles);
                }
            }
        }

        PageResult<RoleDO> pageResult = roleService.queryRolePage(roleQueryDto);
        List<RoleDO> list = pageResult.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(pageResult, Collections.emptyList());
        }
        List<RoleResp> roleRespList = RoleDoToResp.INSTANCE.roleRespList(list);
        processMerchantList(roleRespList);
        return buildPageResult(pageResult, roleRespList);
    }

    @Operation(summary = "角色不分页列表")
    @GetMapping("")
    public CommonResult<List<RoleResp>> queryRoleList(RoleQueryReq roleQueryReq) {
        RoleQueryDto roleQueryDto = new RoleQueryDto();
        roleQueryDto.setLikeName(roleQueryReq.getName());
        roleQueryDto.setSn(roleQueryReq.getSn());
        roleQueryDto.setCode(roleQueryReq.getCode());
        roleQueryDto.setPageNo(roleQueryReq.getPageNo());
        roleQueryDto.setPageSize(roleQueryReq.getPageSize());
        roleQueryDto.setSysType(roleQueryReq.getSysType());

        LocalAdminUserRequest localAdminUserRequest = (LocalAdminUserRequest) LocalContext.get();
        DataFilterConfig dataFilterConfig = platFormConfigService.getDataFilterConfig();
        List<DataFilterConfig.RoleFilter> roleFilters = dataFilterConfig.getRoleFilters();
        Map<Integer, List<DataFilterConfig.RoleFilter>> collect = roleFilters.stream().collect(Collectors.groupingBy(DataFilterConfig.RoleFilter::getSysType));
        List<DataFilterConfig.RoleFilter> roleFilterList = collect.get(localAdminUserRequest.getSysType());

        // 数据进行过滤
        if (!CollectionUtils.isEmpty(roleFilterList)) {
            DataFilterConfig.RoleFilter filter = roleFilterList.get(0);
            roleQueryDto.setFilterCodeList(filter.getRoleCodes());
        }

        boolean isAdmin = false;
        List<AdminUserRoleMappingDO> roleMappingDOList = userService.queryUserRoles(localAdminUserRequest.getUserId());
        if(CollUtil.isNotEmpty(roleMappingDOList)){
            List<String> roles = roleMappingDOList.stream().map(AdminUserRoleMappingDO::getRoleCode).collect(Collectors.toList());
            if(CollUtil.isNotEmpty(roles)){
                // 判断是否含有管理员权限
                isAdmin = roleAppService.isAdmin(roles,roleQueryReq.getSysType());
                if(!isAdmin){
                    roleQueryDto.setCodeList(roles);
                }
            }
        }

        List<RoleDO> list = roleService.queryRoleList(roleQueryDto);
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        List<RoleResp> roleRespList = RoleDoToResp.INSTANCE.roleRespList(list);
        return CommonResult.success(roleRespList);
    }

    @Operation(summary = "角色详情")
    @GetMapping("/detail")
    public CommonResult<RoleDetailResp> queryRoleDetail(@RequestParam("roleCode") String roleCode) {
        return roleAppService.queryRoleDetail(roleCode);
    }

    @Operation(summary = "新增角色")
    @PostMapping("")
    public CommonResult<String> addRole(@Validated @RequestBody RoleAddReq roleAddReq) {
        return roleAppService.addRole(roleAddReq);
    }

    @Operation(summary = "更新角色")
    @PutMapping("")
    CommonResult<Void> updateRole(@Validated @RequestBody RoleUpdateReq roleUpdateReq) {
        return roleAppService.updateRole(roleUpdateReq);
    }

    @Operation(summary = "删除角色")
    @DeleteMapping("")
    CommonResult<Void> deleteRole(@RequestBody DeleteCodeReq deleteCodeReq) {
        return roleAppService.deleteRole(deleteCodeReq.getCode());
    }

    @Operation(summary = "更新角色对应的权限")
    @PostMapping("/permission")
    CommonResult<Void> assignRolePermission(@Validated @RequestBody RolePermissionReq rolePermissionReq) {
        return roleAppService.assignRolePermission(rolePermissionReq);
    }
}
